from sqlalchemy.orm import Session
from sqlalchemy import and_, or_
from . import models
from utils.utils import version2int, int2version
from typing import Optional


# 模板可参考crud.py


async def get_update_rule(
        db: Session,
        version: Optional[str] = None,  # 版本（未使用）
        device_platform: Optional[str] = None,  # 平台(android/ios)
        os_api: Optional[float] = None,  # 系统版本【安卓系统下】
        channel: Optional[str] = None,  # 不同应用商店
        aid: Optional[str] = None,  # app的唯一标识（未使用）
        cpu_arch: Optional[str] = None,  # CPU架构
):
    # 将客户上传update_version_code类型由str转为int
    update_version_code = await version2int(version)
    # 获取所有已上线规则
    rulesObject = db.query(models.Version) \
        .filter(and_(models.Version.is_release == 1,
                     models.Version.is_delete == 0,
                     models.Version.aid == aid,
                     models.Version.cpu_arch == cpu_arch,
                     models.Version.max_os_api >= os_api,
                     models.Version.min_os_api <= os_api,
                     models.Version.max_version >= update_version_code,
                     models.Version.min_version <= update_version_code,
                     models.Version.channel == channel,
                     models.Version.platform == device_platform,
                     )).order_by(models.Version.version.desc()).first()
    return rulesObject
